package com.auto.autoapp.ui.activity

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.util.Function
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.auto.autoapp.R
import com.auto.autoapp.base.BaseActivity
import com.auto.autoapp.databinding.ActivityCommonSettingBinding
import com.auto.autoapp.model.CommonSetting
import com.auto.autoapp.model.SettingType
import com.auto.autoapp.network.RetrofitClient
import com.auto.autoapp.network.SettingInfo
import com.auto.autoapp.ui.activity.LoginActivity
import com.auto.autoapp.util.SpUtil
import com.auto.autoapp.widgets.SimpleToolbar
import com.google.android.material.textfield.TextInputLayout
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CommonSettingActivity : BaseActivity() {
    private lateinit var binding: ActivityCommonSettingBinding
    private var _commonSetting: CommonSetting = SpUtil.getCommonSetting()
    private var _settingInfo: SettingInfo? = null


    override fun provideView(): View {
        binding = ActivityCommonSettingBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun configToolbar(toolbar: SimpleToolbar) {
        super.configToolbar(toolbar)
        toolbar.setTitle("通用设置")
    }

    override fun onInit() {
        initViews()
        setupValidation()
        setupClickListeners()
    }


    fun getCommonSetting() {
        lifecycleScope.launch {
            RetrofitClient.request({
                RetrofitClient.getApi().getSetting(SettingType.COMMON)
            }, iView = this@CommonSettingActivity, onFail = { _, _ ->
                setInitialValue()
            }) { res, _ ->
                _settingInfo = res
                Log.e("TAG", "getCommonSetting: success")
                val infoEmpty = res?.pmvalue.isNullOrEmpty() || res.pmvalue == "{}"
                if (res?.pmtype == SettingType.COMMON && !infoEmpty) {
                    try {
                        _commonSetting = gson.fromJson(res.pmvalue, CommonSetting::class.java)
                    } catch (e: Exception) {
                        Log.e("TAG", "getCommonSetting: ")
                    }
                    setInitialValue()
                }
            }
        }
    }

    private fun saveCommonSetting() {

    }

    private fun setInitialValue() {
        SpUtil.setCommonSetting(_commonSetting)
        binding.tietBrowseDuration.setText(_commonSetting.browseDuration?.toString())
        binding.tietOperationInterval.setText(_commonSetting.operationInterval?.toString())
        binding.tietLikeProbability.setText(_commonSetting.likeProp?.toString())
        binding.tietCommentProbability.setText(_commonSetting.commentProp?.toString())
        binding.tietFollowProbability.setText(_commonSetting.followProp?.toString())
    }

    private fun initViews() {
        getCommonSetting()
    }

    private fun setupValidation() {
        // 为每个输入框添加文本变化监听器
        binding.tietBrowseDuration.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                validateIntegerInput(binding.tilBrowseDuration, s?.toString(), "浏览时长")
            }
        })

        binding.tietOperationInterval.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                validateIntegerInput(binding.tilOperationInterval, s?.toString(), "操作间隔")
            }
        })

        binding.tietLikeProbability.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                validateProbabilityInput(binding.tilLikeProbability, s?.toString(), "点赞概率")
            }
        })

        binding.tietCommentProbability.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                validateProbabilityInput(binding.tilCommentProbability, s?.toString(), "评论概率")
            }
        })

        binding.tietFollowProbability.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                validateProbabilityInput(binding.tilFollowProbability, s?.toString(), "关注概率")
            }
        })
    }

    private fun setupClickListeners() {
        binding.btnConfirm.setOnClickListener {
            if (validateAllFields()) {
                saveSettings()
            }
        }
    }

    /**
     * 验证整数输入
     */
    private fun validateIntegerInput(
        textInputLayout: TextInputLayout,
        value: String?,
        fieldName: String
    ): Boolean {
        return when {
            value.isNullOrEmpty() -> {
                textInputLayout.error = "$fieldName 不能为空"
                false
            }

            !value.matches(Regex("^[0-9]+$")) -> {
                textInputLayout.error = "$fieldName 只能输入数字"
                false
            }

            value.toInt() <= 0 -> {
                textInputLayout.error = "$fieldName 必须大于0"
                false
            }

            else -> {
                textInputLayout.error = null
                true
            }
        }
    }

    /**
     * 验证概率输入（0-100）
     */
    private fun validateProbabilityInput(
        textInputLayout: TextInputLayout,
        value: String?,
        fieldName: String
    ): Boolean {
        return when {
            value.isNullOrEmpty() -> {
                textInputLayout.error = "$fieldName 不能为空"
                false
            }

            !value.matches(Regex("^[0-9]+$")) -> {
                textInputLayout.error = "$fieldName 只能输入数字"
                false
            }

            value.toInt() < 0 || value.toInt() > 100 -> {
                textInputLayout.error = "$fieldName 必须在0-100之间"
                false
            }

            else -> {
                textInputLayout.error = null
                true
            }
        }
    }

    /**
     * 验证所有字段
     */
    private fun validateAllFields(): Boolean {
        val browseDurationValid = validateIntegerInput(
            binding.tilBrowseDuration,
            binding.tietBrowseDuration.text?.toString(),
            "浏览时长"
        )

        val operationIntervalValid = validateIntegerInput(
            binding.tilOperationInterval,
            binding.tietOperationInterval.text?.toString(),
            "操作间隔"
        )

        val likeProbabilityValid = validateProbabilityInput(
            binding.tilLikeProbability,
            binding.tietLikeProbability.text?.toString(),
            "点赞概率"
        )

        val commentProbabilityValid = validateProbabilityInput(
            binding.tilCommentProbability,
            binding.tietCommentProbability.text?.toString(),
            "评论概率"
        )

        val followProbabilityValid = validateProbabilityInput(
            binding.tilFollowProbability,
            binding.tietFollowProbability.text?.toString(),
            "关注概率"
        )

        return browseDurationValid && operationIntervalValid &&
                likeProbabilityValid && commentProbabilityValid && followProbabilityValid
    }

    /**
     * 保存设置
     */
    private fun saveSettings() {
        val browseDuration = binding.tietBrowseDuration.text.toString().toInt()
        val operationInterval = binding.tietOperationInterval.text.toString().toInt()
        val likeProbability = binding.tietLikeProbability.text.toString().toInt()
        val commentProbability = binding.tietCommentProbability.text.toString().toInt()
        val followProbability = binding.tietFollowProbability.text.toString().toInt()
        _commonSetting.browseDuration = browseDuration
        _commonSetting.operationInterval = operationInterval
        _commonSetting.likeProp = likeProbability
        _commonSetting.commentProp = commentProbability
        _commonSetting.followProp = followProbability
        SpUtil.setCommonSetting(_commonSetting)
        lifecycleScope.launch {
            val map = mutableMapOf(
                "pmtype" to SettingType.COMMON,
                "pmvalue" to gson.toJson(_commonSetting)
            )
            if (!_settingInfo?.Id.isNullOrEmpty()) {
                map["id"] = _settingInfo!!.Id!!
            }
            val api = RetrofitClient.getApi().setSetting(map)

            RetrofitClient.request(
                { api },
                iView = this@CommonSettingActivity,
            ) { res, _ ->
                showToast("设置成功")
            }
        }


    }
}